package router

import (
	"iris-wms/common/pkg/db"
	"iris-wms/common/pkg/db/dao"
	"iris-wms/common/tools"
	"iris-wms/common/tools/result"

	"github.com/kataras/iris/v12"
	"gorm.io/gen"
)

func NewWmsHomedataRoute() *wmsHomedataRoute {
	return &wmsHomedataRoute{}
}

type wmsHomedataRoute struct{}

func (r *wmsHomedataRoute) GetHomedata(ctx iris.Context) {
	// nav
	qMenu := dao.Use(db.GDB1).AdminMenuOut
	midList := make([]uint, 0)
	uid := tools.GetUserID(ctx)
	if uid != 1 {
		if err := db.GDB1.Raw(`
		SELECT distinct mid FROM admin_role_menu WHERE rid in (
		SELECT v1 FROM admin_rule WHERE ptype='g' AND v0=?
		)`, uid).Scan(&midList).Error; err != nil {
			return
		}
	}
	condList := make([]gen.Condition, 0)
	if len(midList) > 0 {
		condList = append(condList, qMenu.ID.In(midList...))
	}
	condList = append(condList, qMenu.Name.In([]string{"Goods", "Customer", "Supplier", "Inbound", "Outbound", "Warehouse"}...))

	navList, err := qMenu.Where(condList...).Preload(qMenu.Meta).Find()
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	//
	c1, err := dao.Use(db.GDB1).WmsWarehouseOut.Count()
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	c2, err := dao.Use(db.GDB1).WmsCustomerOut.Count()
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	c3, err := dao.Use(db.GDB1).WmsSupplierOut.Count()
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	// c4, err := dao.Use(db.GDB1).WmsCarrierOut.Count()
	// if err != nil {
	// 	ctx.StopWithPlainError(iris.StatusInternalServerError, err)
	// 	return
	// }
	c5, err := dao.Use(db.GDB1).WmsGoodsOut.Count()
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OKData(ctx, iris.Map{
		"navList":        navList,
		"warehouseCount": c1,
		"customerCount":  c2,
		"supplierCount":  c3,
		// "carrierCount":   c4,
		"goodsCount": c5,
	})
}
